package me.hl.nio;

import org.junit.Test;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

/**
 * Created by Planck on 2016/2/22.
 */
public class ChannleDemo {

    public static FileChannel getChannel(String fileName) {

        try {
            RandomAccessFile randomAccessFile = new RandomAccessFile(fileName, "rw");
            FileChannel fileChannel = randomAccessFile.getChannel();
            return fileChannel;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Test
    public void transformTest() {
        try {
            FileChannel from = getChannel("D://b");
            FileChannel to = getChannel("D://c");

            long position = 0;
            long size = from.size();

            to.transferFrom(from, position, size);
            //方法的输入参数position表示从position处开始向目标文件写入数据，
            // count表示最多传输的字节数。如果源通道的剩余空间小于 count 个字节
            // ，则所传输的字节数要小于请求的字节数。
            //from.transferTo(to,position,size);
            System.out.println("OK");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
